package oa.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;

import oa.web.service.AttenceService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class AttenceController extends BaseController{

	@Autowired
	AttenceService attenceService;
	
	@RequestMapping(value = "validPunch", method = RequestMethod.GET)
	public void validPunch(HttpServletRequest req, HttpServletResponse rep) {
		PrintWriter printWriter = null;
		int punchIsValid = getPunchIsValid(req);
		
//		logger.info("validPunch-----punchIsValid: " + punchIsValid);
		
		try {
			printWriter = rep.getWriter();
			printWriter.write(String.valueOf(punchIsValid));
			printWriter.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(printWriter != null)
				printWriter.close();
		}
		
	}
	
	private int getPunchIsValid(HttpServletRequest req) {
		HttpSession session = req.getSession();
		int currentUserId = 1; //(int) session.getAttribute("currentUserId");
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
		Date date = new Date();
		String dutyDay = dateFormat.format(date);

		int punchIsValid = attenceService.validPunch(currentUserId, dutyDay);
		return punchIsValid;
	}
	
	@RequestMapping(value = "punch", method = RequestMethod.GET)
	public void punch(HttpServletRequest req, HttpServletResponse rep) {
		PrintWriter printWriter = null;
		int punchResult = getPunchResult(req);
		
//		logger.info("punch-----punchResult: " + punchResult);
		
		try {
			printWriter = rep.getWriter();
			printWriter.write(String.valueOf(punchResult));
			printWriter.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(printWriter != null)
				printWriter.close();
		}
	}
	
	private int getPunchResult(HttpServletRequest req) {
		HttpSession session = req.getSession();
		int currentUserId = 1; //(int) session.getAttribute("currentUserId");
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		String dutyDay = "2014-09-14"; //dateFormat.format(date);
		boolean isCome = req.getParameter("isCome") == "1" ? true : false;
		
		int result = attenceService.punch(currentUserId, dutyDay, isCome);
		return result;
	}
	
	@RequestMapping(value = "individualAttence", method = RequestMethod.GET)
	public void individualAttence() {
		
	}
}
